"""
@Author    : ghenyar
@Time      : 2025/8/28 11:10
@File      : __init__.py
@Desc      :  验证码
"""
import os
import random
import base64
import uuid

from captcha.image import ImageCaptcha


class Captcha(object):
    def __init__(self, types: str = "alphabet", size: int = 4):
        # 验证码类型  alphabet:字母   math:数学
        self.type = types
        # 验证码长度 type等于alphabet生效
        self.size = size
        # 验证码字体路径
        # 获取当前文件的绝对路径
        current_file_path = os.path.abspath(__file__)
        self.font = os.path.join(os.path.dirname(current_file_path), "fonts", "GoMonoBoldForPowerline.ttf")

    def generate_captcha(self):
        """
        生成验证码
        :return: {
        'captcha':str, # base64格式的验证码图片数据
        'captcha_key': str, # 验证码key
        'captcha_value':str # 验证码值  验证验证码是要用
        }
        """
        image = ImageCaptcha(fonts=[self.font], height=80)
        captcha_text = ""
        value = None
        if self.type == "alphabet":
            captcha_text = ''.join(random.choice("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(self.size))
            value = captcha_text
        captcha_image = image.generate(captcha_text)
        base64_string = base64.b64encode(captcha_image.getvalue()).decode("utf-8")
        captcha_key = str(uuid.uuid4())
        data = {"captcha": "data:image/png;base64," + base64_string, "captcha_key": captcha_key, "captcha_value": value}
        return data
